package com.zxl.designpattern.creator.builder;

/**
 * @author zxl
 * @version 1.0
 * @description 构建一台电脑，常用的简化版的建造者模式
 * @date 2025/6/1 10:20
 */
public class Computer {

    // CPU
    private final String cpu;
    // 内存
    private final String ram;
    // 显卡
    private final String graphicsCard;
    // 硬盘
    private final String storage;
    // 显示器
    private final String monitor;

    /**
     * 构造函数，使用建造者模式构建电脑
     *
     * @param builder   建造者对象
     */
    public Computer(ComputerBuilder builder) {
        this.cpu = builder.cpu;
        this.ram = builder.ram;
        this.graphicsCard = builder.graphicsCard;
        this.storage = builder.storage;
        this.monitor = builder.monitor;
    }

    @Override
    public String toString() {
        return "Computer{" +
                "cpu='" + cpu + '\'' +
                ", ram='" + ram + '\'' +
                ", graphicsCard='" + graphicsCard + '\'' +
                ", storage='" + storage + '\'' +
                ", monitor='" + monitor + '\'' +
                '}';
    }

    public static class ComputerBuilder {
        private final String cpu;
        private String ram;
        private String graphicsCard;
        private String storage;
        private String monitor;
        private String cpuCooler;

        public ComputerBuilder(String cpu) {
            this.cpu = cpu;
        }

        public static ComputerBuilder getInstance(String cpu) {
            return new ComputerBuilder(cpu);
        }
        public ComputerBuilder setRam(String ram) {
            this.ram = ram;
            return this;
        }
        public ComputerBuilder setGraphicsCard(String graphicsCard) {
            // 模拟装机步骤，显卡必须在内存之后安装。以此来控制创建者的构建顺序
            // 当然，在编程时也可不做要求，这里只是展示控制构建顺序的方法。
            if(ram == null){
                throw new IllegalArgumentException("内存必须先于显卡安装");
            }
            this.graphicsCard = graphicsCard;
            return this;
        }

        public ComputerBuilder setStorage(String storage) {
            this.storage = storage;
            return this;
        }

        public ComputerBuilder setMonitor(String monitor) {
            this.monitor = monitor;
            return this;
        }

        /**
         * 构建电脑
         * @return
         */
        public Computer build() {
            // 可以在此处做最终验证，成功了才创建电脑对象
            return new Computer(this);
        }
    }

}
